<?php

namespace app\api\middleware;

use Exception;
use Firebase\JWT\BeforeValidException;
use Firebase\JWT\ExpiredException;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use Firebase\JWT\SignatureInvalidException;
use think\facade\Request;


/**
 * 中间件
 */
class Auth
{
    //token验证
    public function handle($request, \Closure $next)
    {
        $token = Request::header('Token');
        if (!$token) {
            return json(['code' => 404, 'msg' => 'token不能为空']);
        }

        if (count(explode('.', $token)) != 3) {
            return json(['code' => 404, 'msg' => '非法请求']);
        }

        try {
            $jwt_data = $this->decodeToken($token);
            define('JWT_UID', $jwt_data['userid']);
            return $next($request);
        } catch (SignatureInvalidException $e) {
            return json(['code' => 403, 'msg' => '签名错误']);
        } catch (BeforeValidException $e) {
            return json(['code' => 401, 'msg' => 'token失效']);
        } catch (ExpiredException $e) {
            return json(['code' => 401, 'msg' => 'token已过期']);
        } catch (Exception $e) {
            return json(['code' => 404, 'msg' => '非法请求']);
        }
    }

    private function decodeToken($token)
    {
        $config = get_system_config('token');
        JWT::$leeway = 60;
        $decoded = JWT::decode($token, new Key($config['secrect'], 'HS256'));
        $decoded_array = json_decode(json_encode($decoded), TRUE);
        return $decoded_array['data'];
    }

}
